package org.example.controller;

import org.example.entity.Orders;
import org.example.service.IOrdersService;
import org.example.utils.PageResult;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/orders")
@CrossOrigin
public class OrdersControl {
    @Autowired
    private IOrdersService ordersService;


    @GetMapping("/list")
    public Result finaAll(){
        List<Orders> ordersList = ordersService.list();
        return Result.ok().data("orders",ordersList);
    }


    @GetMapping("/findByPage/{page}/{pageSize}")
    public Result finaByPage(@PathVariable int page, @PathVariable int pageSize){
        PageResult<Orders> pageResult = ordersService.selectByPage(page, pageSize);
        return Result.ok().data("pageResult",pageResult);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Orders orders){
        if (ordersService.addOrder(orders)){
            return Result.ok().message("添加订单成功");
        } else {
            return Result.error().message("添加订单失败");
        }
    }


    @PutMapping("/update")
    public Result update(@RequestBody Orders orders){
        if (ordersService.updateById(orders)){
            return Result.ok().message("修改订单成功");
        } else {
            return Result.error().message("修改订单失败");
        }
    }


    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id){
        if (ordersService.removeById(id) ) {
            return Result.ok().message("删除成功");
        } else {
            return Result.error().message("删除失败");
        }
    }


    @DeleteMapping("/deleteBatch/{ids}")
    public Result deleteBatch(@PathVariable String ids){
        String[] idsArray = ids.split(",");
        List<String> idsList = Arrays.asList(idsArray);
        if (ordersService.removeByIds(idsList) ) {
            return Result.ok().message("删除成功");
        } else {
            return Result.error().message("删除失败");
        }
    }

}
